package com.test.ayi.service;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class EmailServiceImpl implements EmailService {

    public static class EmailContent {
        private Date sentDate;
        private String subject;
        private String plainText;

        // Getters and Setters
        public Date getSentDate() {
            return sentDate;
        }

        public void setSentDate(Date sentDate) {
            this.sentDate = sentDate;
        }

        public String getSubject() {
            return subject;
        }

        public void setSubject(String subject) {
            this.subject = subject;
        }

        public String getPlainText() {
            return plainText;
        }

        public void setPlainText(String plainText) {
            this.plainText = plainText;
        }
    }

    @Override
    public List<EmailContent> receiveWithImap(LocalDate date) throws MessagingException, IOException {
        String user = "chenglongyiyiyi@126.com"; // 邮箱的用户名
        String password = "PMgL7mhCJmWxame6"; // 邮箱的密码

        Properties prop = System.getProperties();
        prop.put("mail.store.protocol", "imap");
        prop.put("mail.imap.host", "imap.126.com");
        prop.put("mail.smtp.auth", "true");

        // 设置IMAP ID信息
        HashMap<String, String> IAM = new HashMap<>();
        IAM.put("name", "myname");
        IAM.put("version", "1.0.0");
        IAM.put("vendor", "myclient");
        IAM.put("support-email", "testmail@test.com");

        Session session = Session.getInstance(prop);
        IMAPStore store = (IMAPStore) session.getStore("imap");
        store.connect(user, password);
        store.id(IAM);

        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);

        List<Message> messages = Arrays.stream(folder.getMessages())
                .filter(e -> {
                    try {
                        // 将 Date 转换为 LocalDate
                        LocalDate localDate1 = e.getSentDate().toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDate();
                        return localDate1.equals(date);
                    } catch (MessagingException ex) {
                        throw new RuntimeException(ex);
                    }
                }).collect(Collectors.toList());

        List<EmailContent> emailContents = new ArrayList<>();
        for (Message message : messages) {
            EmailContent emailContent = new EmailContent();
            emailContent.setSentDate(message.getSentDate());
            emailContent.setSubject(message.getSubject());

            Object content = message.getContent();
            if (content instanceof MimeMultipart) {
                MimeMultipart multipart = (MimeMultipart) content;
                extractContentFromMultipart(multipart, emailContent);
            } else if (content instanceof String) {
                // 如果邮件内容是简单的字符串
                String htmlContent = (String) content;
                // 使用 Jsoup 提取纯文本
                String plainText = org.jsoup.Jsoup.parse(htmlContent).text();
                emailContent.setPlainText(plainText);
            }
            emailContents.add(emailContent);
        }
        folder.close(true);
        store.close();


        return emailContents;
    }

    private static void extractContentFromMultipart(MimeMultipart multipart, EmailContent emailContent)
            throws MessagingException, IOException {
        int count = multipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            processBodyPart(bodyPart, emailContent);
        }
    }

    private static void processBodyPart(BodyPart bodyPart, EmailContent emailContent)
            throws MessagingException, IOException {
        String contentType = bodyPart.getContentType();
        Object content = bodyPart.getContent();

        System.out.println("Processing part with content type: " + contentType);

        if (contentType.contains("text/plain")) {
            // 处理纯文本内容
            if (content instanceof String) {
                String htmlContent = (String) content;
                // 使用 Jsoup 提取纯文本
                String plainText = org.jsoup.Jsoup.parse(htmlContent).text();
                emailContent.setPlainText(plainText);
            }
        } else if (contentType.contains("text/html")) {
            // 处理 HTML 内容
            if (content instanceof String) {
                String htmlContent = (String) content;
                // 使用 Jsoup 提取纯文本
                String plainText = org.jsoup.Jsoup.parse(htmlContent).text();
                emailContent.setPlainText(plainText); // 将提取的纯文本设置为 plainText
            }
        } else if (contentType.contains("multipart/")) {
            // 递归处理嵌套的 Multipart
            if (content instanceof MimeMultipart) {
                extractContentFromMultipart((MimeMultipart) content, emailContent);
            }
        } else {
        }
    }


    /*public static void main(String[] args) throws Exception {
        EmailContent emailContent = receiveWithImap();
        System.out.println("Sent Date: " + emailContent.getSentDate());
        System.out.println("Subject: " + emailContent.getSubject());
        System.out.println("Plain Text: " + emailContent.getPlainText());
        System.out.println("###################################################################");

    }*/
}